package com.qipay.sp.excutor.aliface;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.qipay.baas.model.Order;
import com.qipay.scalar.type.ApiTypeEnum;
import com.qipay.sp.excutor.AbstractExcutor;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Component
public class AliFaceNativeExcutor extends AbstractExcutor {

    private final static String CONFIG_APPID_NAME="appid";
    private final static String CONFIG_ALIPAY_PUBLIC_NAME="rsa_public_key_alipay";
    private final static String CONFIG_RSA_PRIVATE_NAME="rsa_private_key";
    private final static String API_PARAM_OUT_TRADE_NO="out_trade_no";
    private final static String API_PARAM_TOTAL_AMOUNT="total_amount";
    private final static String API_PARAM_SUBJECT="suject";
    private final static String API_PARAM_RETURN_URL="return_url";
    private final static String API_PARAM_NOTIFY_URL="notify_url";
    private final static String API_URL="https://openapi.alipay.com/gateway.do";

    @Override
    protected ApiTypeEnum getApiTypeEnum() {
        return ApiTypeEnum.ALIPAY_NATIVE;
    }

    @Override
    protected Map<String, Object> getApiParams(Order order, Map<String, Object> spconfig, Map<String, Object> extendOrderParams) {
        Map<String, Object> apiParams = new HashMap<>();
        apiParams.put(AliFaceNativeExcutor.API_PARAM_OUT_TRADE_NO, order.getTradeNo());
        apiParams.put(AliFaceNativeExcutor.API_PARAM_SUBJECT, order.getBody());
        apiParams.put(AliFaceNativeExcutor.API_PARAM_TOTAL_AMOUNT, order.getActualPayAmount());

        return apiParams;
    }

    @Override
    protected Map<String, Object> run(Map<String, Object> spconfig, Map<String, Object> params) throws Exception {

        Object appId = getVal(spconfig, AliFaceNativeExcutor.CONFIG_APPID_NAME);
        Object rsaPrivateKey = getVal(spconfig, AliFaceNativeExcutor.CONFIG_RSA_PRIVATE_NAME);
        Object rsaPublicKeyAlipay = getVal(spconfig, AliFaceNativeExcutor.CONFIG_ALIPAY_PUBLIC_NAME);
        Object outTradeNo = getVal(params, AliFaceNativeExcutor.API_PARAM_OUT_TRADE_NO);
        Object totalAmount = getVal(params, AliFaceNativeExcutor.API_PARAM_TOTAL_AMOUNT);
        String amount = new BigDecimal((Integer) totalAmount).divide(new BigDecimal(100)).toString();
        Object subject = getVal(params, AliFaceNativeExcutor.API_PARAM_SUBJECT);
        Object returnUrl = getVal(params, AliFaceNativeExcutor.API_PARAM_RETURN_URL);
        Object notifyUrl = getVal(params, AliFaceNativeExcutor.API_PARAM_NOTIFY_URL);
        Object trans_in = getVal(spconfig, "trans_in");

        AlipayClient alipayClient = new DefaultAlipayClient(AliFaceNativeExcutor.API_URL, appId.toString(), rsaPrivateKey.toString(), "json", "UTF-8", rsaPublicKeyAlipay.toString(), "RSA2"); // 获得初始化的AlipayClient
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();//创建API对应的request类
        request.setReturnUrl(returnUrl.toString());
        request.setNotifyUrl(notifyUrl.toString());
        request.setBizContent("{" +
                "    \"out_trade_no\":\""+outTradeNo+"\"," +
                "    \"total_amount\":\""+amount+"\"," +
                "    \"subject\":\""+subject+"\"," +
                "    \"store_id\":\"NJ_001\"," +
                "    \"extend_params\":{" +
                "    \"sys_service_provider_id\":\""+trans_in+"\"" +
                "    }," +
                "    \"timeout_express\":\"90m\"}");//设置业务参数
        AlipayTradePrecreateResponse response = null;

        Map<String, Object> resultMap = new HashMap<>();
        try {
            response = alipayClient.execute(request);
        }catch (Exception e){
            resultMap.put("result_code", "1");
            resultMap.put("message", "支付宝接口异常");
        }
        if(response!=null){
            if(response.isSuccess()){
                resultMap.put("result_code", "0");
                resultMap.put("code_url", response.getQrCode());
            } else {
                logger.info("支付宝当面付接口请求失败：" + JSONObject.toJSONString(response));
                resultMap.put("result_code", "1");
                resultMap.put("message", response.getMsg());
            }
        }
        return resultMap;
    }
}
